package com.example.my_music_palyer.common.tools;


import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.exceptions.CannotReadException;
import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException;
import org.jaudiotagger.audio.exceptions.ReadOnlyFileException;
import org.jaudiotagger.audio.mp3.MP3File;
import org.jaudiotagger.tag.TagException;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;

public class Mp3Tag {
    //判断是否是MP3格式的文件（看ID3V1的TAG标识）

    public static boolean hasID3V1Tag(String musicPath) throws IOException {
        File musicFile = new File(musicPath);
        FileInputStream fileInputStream = new FileInputStream(musicFile);
        // MP3 文件的ID3V1的 TAG 标识 在ID3V1（固定文件的最后128字节）的前3个字节
        byte[] tag = new byte[3];
        //将光标跳到 倒数128字节的位置
        if(musicFile.length() < 128){
            return false;
        }


        fileInputStream.skip(musicFile.length()-128);

        //读取tag标识
        fileInputStream.read(tag);

        System.out.println("----------------------");
        System.out.println(tag.toString());
        System.out.println("----------------------");

        StringBuffer TAG = new StringBuffer();
        for (byte x: tag){
            TAG.append((char) x);
        }

        String ret = TAG.toString();
        if(ret.equals("TAG")) {
            System.out.println("是MP3文件");
            return true;
        }else {
            System.out.println("不是MP3文件");
            System.out.println(ret);
            return false;
        }

    }



    public static void main(String[] args) throws IOException {
        String musicPath = "E:/JAVACODE/music/musicData/鼓楼.mp3";
        File musicFile = new File(musicPath);
        FileInputStream fileInputStream = new FileInputStream(musicFile);
        // MP3 文件的ID3V1的 TAG 标识 在ID3V1（固定文件的最后128字节）的前3个字节
        byte[] tag = new byte[3];
        //将光标跳到 倒数128字节的位置
        System.out.println("--------");
        System.out.println(musicFile.length());
        System.out.println(musicFile.length()-128);
        System.out.println("--------");

        byte[] bytes = Files.readAllBytes(Paths.get(musicPath));
        String s = new String(bytes);
        System.out.println(s);
        System.out.println("--------");

        fileInputStream.skip(musicFile.length()-128);
        //读取tag标识
        fileInputStream.read(tag);

        StringBuffer TAG = new StringBuffer();
        for (byte x: tag){
            TAG.append((char) x);
        }
        String ret = TAG.toString();
        if(ret.equals("TAG")) {
            System.out.println("是MP3文件");;
        }else {
            System.out.println("不是MP3文件");
        }
    }

}
